import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { NotificationService } from "../../../shared/utils/notification.service";
declare var $: any;
declare var BMap: any;
declare var BMapLib: any;
declare var echarts: any;
declare var toMapPoint: any;
declare var BMAP_ANCHOR_BOTTOM_RIGHT: any;
@Component({
	selector: 'sa-taskBoard',
	templateUrl: './taskBoard.component.html',
	styleUrls: ['./taskBoard.css']
})
export class TaskBoardComponent implements OnInit {
	tableData = []; //table数据
	selected = []; //row选择的数据
	totalCount = 0; //分页总条数
	curPage = 1; //分页当前页
	pageSize = 12; //内置的分页每页条数
	searchKey = ''; //搜索keyword
	carList = [];
	deviceId = ''; //设备ID

	mapDeviceId = ''; //地图设备ID
	carNumber = '';
	selectedCarNumber = '';
	selectedCompanyId = '';
	selectedCompanyName = '';
	companyId = '';
	startTime = ''; //开始时间
	endTime = ''; //结束时间
	minStopTime = '60';
	btnNum = 'all'; //table分类按钮状态
	allTotal = 0; //所有车辆
	normalTotal = 0; //正常车辆
	abnormalTotal = 0; //异常车辆
	mapStartTime = '';
	mapEndTime = '';

	cantonName = ''; //行政区域名
	baiduMap: any; //实例化地图对象
	trackData = []; //轨迹路线数据
	carMoveCanvasLayer: any; //移动折线对应地图添加点的,
	boundaryRegion: any; //行政边界区域构造器
	areaPly; //行政边界区域的覆盖图形

	isEnter = true; //默认选中进入特价区域

	inTimeArr = []; //存储进入边界的时间,对应outTimeArr离开边界的时间
	outTimeArr = [];

	inRegionTime = ''; //进入边界时间
	outRegionTime = ''; //进入边界后离开时间
	myChart: any; //实例化折线图对象
	chartOption: any; //折线图配置
	xAxisData = []; //折线图X轴时间数据
	yAxisWeight = []; //重量折线数据
	yAxisSpeed = []; //速度折线数据
	//基本信息
	basInformation = [];

	activeSelected: string = '';

	constructor(private jsonApiService: JsonApiService, private activatedRoute: ActivatedRoute, private router: Router, private notificationService: NotificationService, ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			if(queryParams.nowPage) {
				this.curPage = queryParams.nowPage;
			}

		});
	}

	ngOnInit() {

		//初始化地图
		this.initBaiduMap();
		//初始化一个行政边界区域构造器
		this.boundaryRegion = new BMap.Boundary();

		//初始化数据;
		this.initBasInformation();

		//初始化日期,加载table表格数据
		this.initDate().then(() => {
			this.dataClassify();
			this.load();

		});
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.selectCompany(); //初始化select 2 车辆
				this.queryCarListByCompanyId('5c00ff008607352c75ab849e');
			})
			//			System.import('assets/js/jstree/jstree.min.js').then(()=>{
			//				this.initCompanyList();//初始化公司树
			//				var tree_box = document.getElementById('tree_box');
			//				var company = document.getElementById('company');
			//公司树弹窗显示隐藏交互事件
			//				document.onclick=function(e:any){
			//					if(!(e.target === company||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
			//				        tree_box.className = tree_box.className.replace("tree_open","");
			//				   	} 
			//				}
			//			})
		})

		
		//初始化页面视图
		this.initPageView();
	}
	baiduMapTools: any;
	//初始化页面视图
	initPageView() {
		//初始化加载头部数据统计
		this.dataClassify();
		//初始化清空基本信息
		this.initBasInformation();
		//初始化chart图内容
		this.initChart();
		//清空地图轨迹
		// clearTrackLine(this.baiduMap);
		//清空行政区域
		this.baiduMap.removeOverlay(this.areaPly);
	}

	//初始化基本信息
	initBasInformation() {
		this.basInformation = [{
				name: 'carNumber',
				value: '',
				textStr: '车牌'
			},
			{
				name: 'dealer',
				value: '',
				textStr: '经销商'
			},
			{
				name: 'goods',
				value: '',
				textStr: '货物'
			},
			{
				name: 'weight',
				value: '',
				textStr: '净重'
			},
			{
				name: 'loadTime',
				value: '',
				textStr: '装载耗时'
			},
			{
				name: 'leaveDate',
				value: '',
				textStr: '发车时间'
			},
			{
				name: 'transportTime',
				value: '',
				textStr: '运输时长'
			},
			{
				name: 'unloadTime',
				value: '',
				textStr: '卸载耗时'
			},
			{
				name: 'unloadEndDate',
				value: '',
				textStr: '卸货完成时间'
			},
			{
				name: 'unloadArea',
				value: '',
				textStr: '目的地'
			},
			{
				name: 'unloadAddress',
				value: '',
				textStr: '卸货地址'
			},
		]
	}
	//初始地图
	initBaiduMap() {

		let map = new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		map.centerAndZoom(new BMap.Point(117.7953288, 28.2862345), 5); //初始化地图，设置中心点坐标和地图级别
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		map.addControl(new BMap.NavigationControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,offset: new BMap.Size(12, 68)}));//地图缩放控件
		this.baiduMap = map;
	}	

	//初始折线图
	initChart() {
		this.chartOption = {
			title: {
				text: '重量曲线',
				left: 'center',
				textStyle: {
					fontSize: 15,
				}
				//		        subtext: '灰色标题'
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross'
				},
				formatter: function(params) {
					var paramIndex = params[0].dataIndex;
					var pointObj = this.trackData[paramIndex];
					if(!pointObj || pointObj.x == '' || pointObj.x == '0') {
						return;
					}
					this.lineMoveCarPoint(pointObj)
					var res = '';
					var len = params.length;
					for(var i = 0; i < len; i++) {
						res = res + params[i].marker + params[i].seriesName + ':' + params[i].data + '</br>'
					}
					return res;
				}.bind(this)
			},
			grid: {
				left: '48px',
				right: '36px',
				top: '60px',
				bottom: '24px'
			},
			toolbox: {
				show: false,
			},
			legend: {
				top: '20px'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
//		        data: ['00:00', '01:15', '02:30', '03:45', '05:00', '06:15', '07:30', '08:45', '10:00', '11:15', '12:30', '13:45', '15:00', '16:15', '17:30', '18:45', '20:00', '21:15', '22:30', '23:45']
				data: []
			},
			yAxis: [{
					name: '吨',
					type: 'value',
					axisLabel: {
						formatter: '{value}'
					},
					axisPointer: {
						snap: true
					}
				},
				{
					name: 'km/h',
					splitLine: {      
						show: false    
					},
					type: 'value',
					axisLabel: {
						formatter: '{value}'
					},
					axisLine: {
						lineStyle: {
							color: '#5793f3'
						}
					},
				},
			],
			series: [{
					name: '重量',
					type: 'line',
					smooth: true,
//		            data: [300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
					data: [],
					markArea: {
						data: [
							[{
								name: '',
								xAxis: ''
							}, {
								xAxis: ''
							}]
						]
					}
				},
				{
					name: '速度',
					type: 'line',
					smooth: true,
					yAxisIndex: 1,
					data: [],
					itemStyle: {
						//样式
						normal: {
							color: '#5793f3',
							lineStyle: {
								width: 1, //折线宽度
								opacity: 0.5,
							}
						}
					},
					areaStyle: {
						//阴影
						color: 'rgba(83, 146, 230,0.5)'
					}
				}
			]
		};
		this.myChart = echarts.init(document.getElementById('myChart'));
		this.myChart.setOption(this.chartOption, true);
		var that = this;
		$(window).resize(function() {
			//当浏览器大小变化时重新计算图表
			that.myChart.resize();
		});
	}

	//数据分类
	dataClassify() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
		this.jsonApiService.http("transportTask/countForTask.html", reqdata).subscribe(data => {
			if(data && data.data) {
				this.allTotal = data.data[0];; //所有车辆
				this.normalTotal = data.data[1];; //正常车辆
				this.abnormalTotal = data.data[2];; //异常车辆
			}
		})

	}

	//加载list数据
	load() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		this.initPageView();
		var dataType = '';
		if(this.btnNum == 'normal') {
			dataType = '1'
		} else if(this.btnNum == 'abnormal') {
			dataType = '-1'
		}
		this.endTime = $('#datetimepicker2').val();
		let param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				deviceId: this.deviceId,
				startTime: this.startTime,
				endTime: this.endTime,
				status: dataType,
				searchKey: this.searchKey,
			}
		};
		let reqdata = 'gridPager=' + JSON.stringify(param);
		//		let reqdata = 'gridPager={"parameters":{"deviceId":"'+this.deviceId+'","startTime":"'+this.startTime+'","endTime":"'+this.endTime+'","searchKey":"'+this.searchKey+'","dataType":"3"}}'
		this.jsonApiService.http("transportTask/taskListForpage.html", reqdata).subscribe(data => {
			if(data.isSuccess) {
				for(var i = 0; i < data.exhibitDatas.length; i++) {
					if(data.exhibitDatas[i].weight < 0) {
						if(data.exhibitDatas[i].weight > -1) {
							data.exhibitDatas[i].weight = 0;
						}
					}
					data.exhibitDatas[i].weight = common.twoDecimal(data.exhibitDatas[i].weight) + '吨';
					//转换时间格式
					data.exhibitDatas[i].loadTime = lostTimeStr(data.exhibitDatas[i].loadTime);
					data.exhibitDatas[i].transportTime = lostTimeStr(data.exhibitDatas[i].transportTime);
					data.exhibitDatas[i].unloadTime = lostTimeStr(data.exhibitDatas[i].unloadTime);
				}
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}
	//删除所选时间
	del_date() {
		this.startTime = '';
		this.endTime = '';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}

	//表格选择一行获取数据,请求后台获取折线图数据跟轨迹图数据并加载地图跟折线图
	rowSelectEvent(row) {
		this.activeSelected = row.id;
		if(!row.finish) {
			var statuStr = '';
			switch(row.status) {
				case 2:
					statuStr = '在途';
					break;
				case 3:
					statuStr = '在场';
					break;
			}
			this.message('改车辆处于' + statuStr + '状态,暂不提供数据查询...');
			return;
		}
		this.cantonName = row.unloadArea;
		this.baiduMap.closeInfoWindow();
		this.baiduMap.removeOverlay(this.carMoveCanvasLayer);

		function nullUpdate() {}
		this.carMoveCanvasLayer = new CanvasLayer({
			map: this.baiduMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.baiduMap.addOverlay(this.carMoveCanvasLayer);

		this.carNumber = row.carNumber;
		this.mapDeviceId = row.deviceId;
//		this.mapStartTime = row.enterDate;
//		this.mapEndTime = row.emptyDate;
		let time1=common.getTimeMmss(new Date(common.mmsstoTimestamp(row.loadStartDate)-30*60*1000));//开始装货前半小时
		let time2=common.getTimeMmss(new Date(common.mmsstoTimestamp(row.emptyDate)+30*60*1000));//卸货完成后半小时
		this.mapStartTime = time1;
		this.mapEndTime = time2;
		layer.load();

		for(var i = 0; i < this.basInformation.length; i++) {
			var itemName = this.basInformation[i].name;
			if(itemName === 'weight') {
				this.basInformation[i].value = row[itemName] == null ? '--' : row[itemName];
			} else {
				this.basInformation[i].value = row[itemName] ? row[itemName] : '--';
			}
		}
		this.askforData().then(() => {
			this.mapDeviceId = '';
			this.drawBoundary();
		});

	}

	askforData() {
		return new Promise(function(resolve, reject) {
			this.trackData = [];
			this.xAxisData = [];
			this.yAxisWeight = [];
			this.yAxisSpeed = [];
			//			this.startTime='2018-10-11 11:30:26';
			//			this.endTime='2018-10-12 00:00:26';
			let reqdata = 'deviceId=' + this.mapDeviceId + '&startTime=' + this.mapStartTime + '&endTime=' + this.mapEndTime + '&showModify=' + false;

			this.jsonApiService.http("stats/draw.html", reqdata).subscribe(result => {
				var len = result.data.length;
				if(len < 2) {
					layer.closeAll('loading');
					this.jsonApiService.message('该时间段没有数据...')
					return;
				}

				for(var i = 0; i < len; i++) {
					var mapPoint = toMapPoint(result.data[i]);
					if(mapPoint) {
						this.trackData.push(mapPoint);
					}
					this.xAxisData.push(result.data[i].uploadDate);
					this.yAxisWeight.push(result.data[i].weight);
					this.yAxisSpeed.push(result.data[i].speed);
				}
				resolve();
			})
		}.bind(this))
	}

	//画轨迹图
	drawTrackLine() {
		var geturl = config.BaseURL;
		let lineStyle = {
			star: true,
			end: false,
			color: true,
			infoUrl: geturl
		};
		drawTrackLine(this.trackData, this.baiduMap, lineStyle);
	}

	//绘画行政区域边界
	drawBoundary() {
		var that = this;
		if(that.cantonName == '' || !that.cantonName) {
			this.drawChart();
			this.drawTrackLine();
			that.baiduMap.removeOverlay(that.areaPly);
			var centerPoint = new BMap.Point(this.trackData[0].lng, this.trackData[0].lat);
			that.baiduMap.centerAndZoom(centerPoint, 10);
			return;
		}
		this.boundaryRegion.get(that.cantonName, function(rs) { //获取行政区域
			that.baiduMap.removeOverlay(that.areaPly); //清除掉之前的边界区域
			var count = rs.boundaries.length; //行政区域的点有多少个
			that.inRegionTime = '';
			that.outRegionTime = '';
			if(count < 1) {
				return;
			}
			that.areaPly = new BMap.Polygon(rs.boundaries[0], {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //建立多边形覆盖物
			that.baiduMap.addOverlay(that.areaPly); //添加覆盖物
			that.baiduMap.setViewport(that.areaPly.getPath()); //调整视野  
			that.drawTrackLine();
			that.inTimeArr = [];
			that.outTimeArr = [];

			function getInOutTimeArr(order) {
				var isOut = false; //判断是否再进入边界后又再次出去
				var len = that.trackData.length;
				for(var i = order; i < len; i++) {
					var comparePoint = new BMap.Point(that.trackData[i].lng, that.trackData[i].lat);
					var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
					if(result) { //在内部，把该点显示在地图上  
						that.inTimeArr.push(that.trackData[i].uploadDate);
						for(var j = i; j < len; j++) {
							var comparePoint = new BMap.Point(that.trackData[j].lng, that.trackData[j].lat);
							var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, that.areaPly);
							if(!result) { //在内部，把该点显示在地图上  
								isOut = true; //判断是否再进入边界后又再次出去
								that.outTimeArr.push(that.trackData[j].uploadDate);
								if(j < len) {
									getInOutTimeArr(j);
								}
								break;
							}
						}
						if(!isOut) {
							that.outTimeArr.push(that.trackData[len - 1].uploadDate);
						}
						break;
					}
				}
			}
			getInOutTimeArr(0);
			that.drawChart();
		})
	}

	//画折线图
	drawChart() {
		layer.closeAll('loading');
		this.chartOption.xAxis.data = this.xAxisData;
		this.chartOption.series[0].data = this.yAxisWeight;

		this.chartOption.series[1].data = this.yAxisSpeed;
		var len = this.xAxisData.length;

		if(this.isEnter) {

			var timeShadow = [];

			for(var i = 0; i < this.inTimeArr.length; i++) {

				var dataArr = [{
						name: '进入特价区域',
						xAxis: this.inTimeArr[i]
					},
					{
						xAxis: this.outTimeArr[i]
					}
				]
				timeShadow.push(dataArr)
			}

			this.chartOption.series[0].markArea.data = timeShadow;
			//			this.chartOption.series[0].markArea= {
			//              data: [ 
			//              	[{
			//	                    name: '进入特价区域',
			//	                    xAxis: this.inRegionTime
			//              	}, 
			//              	{
			//                  	xAxis: this.outRegionTime
			//             	 	}]]
			//          }

		}
		this.myChart.setOption(this.chartOption, true);

		//点击折线图  地图展开信息框
		//		var that=this;
		//		this.myChart.on('click', function(params) {
		//			var pointObj= that.trackData[params.dataIndex];
		//			if(pointObj == undefined) {
		//				return;
		//			}
		//			var geturl=config.BaseURL;
		//			common.createInfoBox(that.baiduMap,pointObj,geturl);
		//		})

	}

	//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		if(data.lat > 0) {
			var mp = this.baiduMap;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if(!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};

			if(typeof this.carMoveCanvasLayer != 'undefined') {
				this.carMoveCanvasLayer.options.update = update;
				this.carMoveCanvasLayer._draw();
				return;
			}
			this.carMoveCanvasLayer = new CanvasLayer({
				map: this.baiduMap,
				update: update,
				zIndex: 10
			});

		}
	}

	//是否进入特价区域复选框变更事件
	isEnterChange() {

		var len = this.trackData.length;
		if(len < 2) {
			return
		}
		if(this.isEnter) {
			var timeShadow = [];
			for(var i = 0; i < this.inTimeArr.length; i++) {
				var dataArr = [{
					name: '进入特价区域',
					xAxis: this.inTimeArr[i]
				}, {
					xAxis: this.outTimeArr[i]
				}]
				timeShadow.push(dataArr)
			}
			this.chartOption.series[0].markArea.data = timeShadow;
		} else {
			this.chartOption.series[0].markArea = {
				data: [
					[{
						name: '',
						xAxis: ''
					}, {
						xAxis: ''
					}]
				]
			}

		}
		this.myChart.setOption(this.chartOption, true);

	}

	//带确认的信息提示
	confirm_message(message) {
		return new Promise(function(resolve, reject) {
			this.notificationService.smartMessageBox({
				title: "提示",
				content: message,
				buttons: '[确认][取消]'
			}, (ButtonPressed) => {
				if(ButtonPressed === "确认") {
					resolve();
				}
				if(ButtonPressed === "取消") {
					this.notificationService.smallBox({
						content: "操作取消",
						timeout: 3000
					});
					return;
				}

			});
		}.bind(this))
	}
	//信息提示
	message(data) {
		this.notificationService.smallBox({
			content: data,
			timeout: 3000
		});
	}

	//时间转换
	getTime(date) {
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	}

	//初始化日期
	initDate() {
		var that = this;
		return new Promise(function(resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#datetimepicker1").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
						//minView : 2
					}).on("changeDate", function(e) {
						var date = e.date;
						if(!date) {
							return;
						}
						var time = that.getTime(date);
						that.startTime = time;
						$("#datetimepicker2").datetimepicker("setStartDate", time);
					});
					$("#datetimepicker2").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
						//minView : 2
					}).on("changeDate", function(e) {
						var date = e.date;
						if(!date) {
							return;
						}
						var time = that.getTime(date);
						that.endTime = time;
						$("#datetimepicker1").datetimepicker("setEndDate", time);
					});
					//						var date = new Date();
					//						$("#datetimepicker2").val(that.getTime(date));//当前时间
					//						date.setDate(date.getDate() - 7);//设置前一周
					//						$("#datetimepicker1").val(that.getTime(date));
					resolve();
				});
			});
		})

	}
	//擦除公司所选值
	delText() {
		this.selectedCompanyName = '';
		this.selectedCompanyId = '';
		this.selectedCarNumber = '';
		this.deviceId = '';
		this.clearSelect2($("#carNumberSelect2")); //清除Select中的数据
		this.selectCompany();
		$('#company').val("");
		this.companySearch();
		if($('#tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#company').focus();
		}
	}
	//打开公司树
	companyClick() {
		$('#tree_box').toggleClass('tree_open');
	}
	//公司树模糊搜索
	companySearch() {
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1) {
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
					scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3
				});
			}
		})
	}
	//初始化公司树数据
	initCompanyList() {
		var that = this;
		$('#tree').jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "POST",
				        url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {
							withCredentials: true
						},
//				        async: false,
				        success: function(result) {
							jsonarray = result;  
							callback.call(this, jsonarray); 
						}         
					});    
				},
				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.selectedCompanyName = currentNode.text;
			that.selectedCompanyId = currentNode.id;
			that.queryCarListByCompanyId(currentNode.id);
			$('#company').val(currentNode.text).change();
			that.companySearch();
		})
	}
	//擦除车牌号码所选值
	del_carNumber() {
		this.deviceId = '';
		this.selectedCarNumber = '';
		if(this.selectedCompanyId) {
			this.queryCarListByCompanyId(this.selectedCompanyId)
		} else {
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title", "");
			$("#select2-carNumberSelect2-container").prepend(str);
		}
	}
	//初始化select2 车辆选项
	selectCompany() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function(params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function(e) {
			var data = e.params.data;
			that.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.selectedCarNumber = data.text.split('[')[0];
			} else {
				that.selectedCarNumber = data.text;
			}
		});
	}
	//select2 格式回调函数
	formatRepo(state) {
		if(!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除select2 数据
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId) {
		let reqdata = 'companyId=' + companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
			var selectdata = [];
			for(var i = 0; i < carlist.length; i++) {
				var obj = {
					id: carlist[i].deviceId,
					text: carlist[i].carNumber,
				}
				selectdata[i] = obj;
			}
			this.carList = selectdata;
			var selectObj = $("#carNumberSelect2");
			this.clearSelect2(selectObj); //清除Select中的数据
			selectObj.select2({
				language: "zh-CN",
				data: selectdata, //为Select添加数据
				templateResult: this.formatRepo
			});
		})
	}
	//刷新
	refresh() {
		this.load();
	}
	//数据分类按钮点击事件
	btnClick(type) {
		this.btnNum = type;
		this.activeSelected = '';
		this.curPage = 1;
		this.load();
	}
	//查询
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.selectedCarNumber);
		this.load();
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.load();
	}
	//  分页pageSize回调事件
	updatePageSize(e) {
		this.curPage = 1;
		this.pageSize = parseInt(e);
		this.load();
	}
}